#include "StdAfx.h"
#include "FontManager.h"
#include "Font.h"

namespace rkt
{

	IFont*	FontManager::createFont(IRenderSystem* pRenderSystem,ITextureManager* pTextureManager,const char* name,const char* szFontName,uint size)
	{
		Font *pFont = new Font(this);
		if(pFont)
		{
			if(!pFont->create(pRenderSystem,pTextureManager,szFontName,size))
			{
				delete pFont;
				pFont = 0;
			}
			else
			{
				m_sf[name] = pFont;
				m_fs[pFont] = name;
			}
		}

		return pFont;
	}

	void 	FontManager::releaseFont(IFont* pFont)
	{
		if(pFont)
		{
			static_cast<Font*>(pFont)->destroy();
			m_fs.erase(pFont);
			StringFont::iterator e = m_sf.end();
			for(StringFont::iterator it = m_sf.begin();it != e;)
			{
				if((*it).second == pFont)
				{
					m_sf.erase(it++);
				}
				else
				{
					++it;
				}
			}
		}
	}

	void 	FontManager::releaseFont(const char* name)
	{
		if(m_sf.find(name) != m_sf.end())return;

		m_sf.erase(name);
		FontString::iterator e = m_fs.end();
		for(FontString::iterator it = m_fs.begin();it != e;)
		{
			if((*it).second == name)
			{
				static_cast<Font*>((*it).first)->destroy();
				m_fs.erase(it++);
			}
			else
			{
				++it;
			}
		}
	}

	void 	FontManager::releaseAll()
	{
		FontString::iterator e = m_fs.end();
		for(FontString::iterator it = m_fs.begin();it != e;++it)
		{
			static_cast<Font*>((*it).first)->destroy();
		}
		m_fs.clear();
		m_sf.clear();
	}

	IFont*	FontManager::getFontByName(const char* name)
	{
		StringFont::iterator it = m_sf.find(name);
		if(it != m_sf.end())
			return (*it).second;

		return 0;
	}

}